/**
 * 物品列表状态管理
 */
import { defineStore } from 'pinia'
import { getItemsList, getCategories } from '@/api/items'
import type { Item, Category, ItemsFilter, ItemsResponse, CategoriesResponse } from '@/types/items'

export const useItemsStore = defineStore('items', {
  state: () => ({
    items: [] as Item[],
    total: 0,
    loading: false,
    categories: [] as Category[],
    categoriesLoading: false,
    viewMode: 'card' as 'card' | 'table', // 视图模式：卡片或表格
    filters: {
      page: 1,
      pageSize: 20,
      search: '',
      category: 'all',
      propType: '',
      minPrice: null,
      maxPrice: null,
      grade: 'all',
      sort: 'default'
    } as ItemsFilter
  }),

  getters: {
    // 获取总页数
    totalPages: (state) => {
      return Math.ceil(state.total / state.filters.pageSize)
    }
  },

  actions: {
    /**
     * 获取物品列表
     */
    async fetchItems() {
      this.loading = true
      try {
        const response = await getItemsList(this.filters)
        if (response && response.code === 1) {
          this.items = response.data.items || []
          this.total = response.data.total || 0
        } else {
          console.error('获取物品列表失败:', response?.message || '未知错误')
        }
      } catch (error) {
        console.error('获取物品列表异常:', error)
      } finally {
        this.loading = false
      }
    },

    /**
     * 获取物品分类
     */
    async fetchCategories() {
      this.categoriesLoading = true
      try {
        const response = await getCategories()
        if (response && response.code === 1) {
          this.categories = response.data.categories || []
        } else {
          console.error('获取分类列表失败:', response?.message || '未知错误')
        }
      } catch (error) {
        console.error('获取分类列表异常:', error)
      } finally {
        this.categoriesLoading = false
      }
    },

    /**
     * 更新筛选条件
     */
    updateFilters(filters: Partial<ItemsFilter>) {
      // 如果更新了非分页相关的筛选条件，重置页码
      if (Object.keys(filters).some(key => key !== 'page' && key !== 'pageSize')) {
        this.filters.page = 1
      }
      
      // 更新筛选条件
      this.filters = { ...this.filters, ...filters }
      
      // 重新获取物品列表
      this.fetchItems()
    },

    /**
     * 设置视图模式
     */
    setViewMode(mode: 'card' | 'table') {
      this.viewMode = mode
    },

    /**
     * 重置筛选条件
     */
    resetFilters() {
      this.filters = {
        page: 1,
        pageSize: 20,
        search: '',
        category: 'all',
        propType: '',
        minPrice: null,
        maxPrice: null,
        grade: 'all',
        sort: 'default'
      }
      this.fetchItems()
    }
  }
}) 